package com.xiaoyu.lanling.feature.coin.activity

import `in`.srain.cube.app.lifecycle.AppActivityLifecycleCallbacks
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import com.xiaoyu.base.app.App
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseDialogFragment
import com.xiaoyu.lanling.feature.coin.data.CoinEventLogManger
import com.xiaoyu.lanling.router.Router
import kotlinx.android.synthetic.main.coin_recharge_with_first_charge_dialog.*

class CoinRechargeWithFirstChargeDialogFragment : BaseDialogFragment() {

    companion object {

        private val TAG = CoinRechargeWithFirstChargeDialogFragment::class.java.simpleName

        fun show() {
            if (!AppActivityLifecycleCallbacks.getInstance().isAppInForeground) {
                return
            }
            (App.getInstance().topActivity as? FragmentActivity)?.let {
                if (it.isFinishing || it.isDestroyed) {
                    return@let
                }
                val dialogFragment = (it.supportFragmentManager.findFragmentByTag(TAG) as? CoinRechargeWithFirstChargeDialogFragment)
                        ?: CoinRechargeWithFirstChargeDialogFragment()
                dialogFragment.setOnDismissListener(it as? OnDismissListener)
                dialogFragment.show(it.supportFragmentManager, TAG)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreenDimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.coin_recharge_with_first_charge_dialog, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initBind()
        CoinEventLogManger.firstChargeDialogShow()
    }

    private fun initBind() {
        close.setOnClickDebounceListener {
            CoinEventLogManger.firstChargeDialogCloseClick()
            dismiss()
        }
        charge_button.setOnClickDebounceListener {
            dismiss()
            CoinEventLogManger.firstChargeDialogChargeClick()
            activity?.let {
                Router.instance.gotoCoinProductListAndBalanceActivity(it)
            }
        }
        task_button.setOnClickDebounceListener {
            dismiss()
            CoinEventLogManger.firstChargeDialogEarnFreeCoinClick()
            activity?.let {
                Router.instance.gotoMissionListActivity(it)
            }
        }
    }
}